package payutils

import (
	"bytes"
	"crypto/tls"
	"errors"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

// 发送Xml请求
func SendXmlRequest(method, path string, xmlString string, tlsConfig *tls.Config, timeout time.Duration) (body []byte, err error) {
	req, err := http.NewRequest(method, path, bytes.NewBufferString(xmlString))
	if err != nil {
		return
	}
	client := http.Client{}
	if timeout > 0 {
		client.Timeout = timeout * time.Second
	}
	if tlsConfig != nil {
		client.Transport = &http.Transport{TLSClientConfig: tlsConfig}
	}
	resp, err := client.Do(req)
	if err != nil {
		err = errors.New("request fail")
		return
	}
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	return
}

// map转xml
func Map2Xml(params map[string]interface{}) string {
	paramsNew := make(map[string]string)
	for k, v := range params {
		if s, ok := v.(string); ok {
			paramsNew[k] = s
		} else if _, ok := v.(int); ok {
			paramsNew[k] = strconv.Itoa(v.(int))
		} else {
			panic("格式错误，map 格式只支持string, int")
		}
	}
	xmlString := "<xml>"
	for k, v := range paramsNew {
		xmlString += fmt.Sprintf("<%s>%s</%s>", k, v, k)
	}
	xmlString += "</xml>"
	return xmlString
}

// 产生随机字符串
func GetNonceStr(n int) string {
	chars := []byte("abcdefghijklmnopqrstuvwxyz0123456789")
	value := []byte{}
	m := len(chars)
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < n; i++ {
		value = append(value, chars[r.Intn(m)])
	}
	return string(value)
}
